package com.luke.exercise.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class FutureDemo {

    private static final int POOL_SIZE = 10;
    
    static class CalThread implements Callable<Double> {

        private List<Double> dataList = new ArrayList<Double>();
        
        public CalThread() {
            for(int i=0 ; i<10000 ; i++) {
                dataList.add(Math.random());
            }
        }
        
        public Double call() throws Exception {
           double total = 0;
           for(Double d : dataList) {
               total += d;
           }
           return total;
        } 
    }
    
    public static void main(String[] args) {
        List<Future<Double>> list = new ArrayList<Future<Double>>();
        ExecutorService service = Executors.newFixedThreadPool(POOL_SIZE);
        for(int i=0 ; i<POOL_SIZE ; ++i) {
            list.add(service.submit(new CalThread()));
        }
        
        for(Future<Double> f : list) {
            try {
                System.out.println(f.get());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        service.shutdown();
    }
}
